package com.starblink.search.result.ui.fragment.post

import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.android.material.button.MaterialButton
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.android.common.adapter.cell.DiscoverPostCardCell
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.rocketreserver.fragment.PostF
import com.starblink.search.databinding.FgmSearchPostResultBinding

/**
 * 内容结果
 */
internal class PostResultFragment :
    BaseTVMLazyLoadingFragment<FgmSearchPostResultBinding, PostResultVM>() {

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.contentList).apply {
            addVhDelegate {
                DiscoverPostCardCell(
                    it,
                    viewModel.contentList,
                    RoutePage.Post.SCENE.SEARCH.value,
                    viewModel.keyWord,
                    viewModel.pageNo,
                    viewModel.type ?: -1, spmPageValue = SpmPageDef.SearchRoute
                ) {
                }
            }
//            addVhDelegate {
//                PostBannerHolder(
//                    activity, viewModel.contentList,
//                    ItemPostBannerBinding.inflate(it.inflater, it, false),
//                )
//            }
        }
    }


    override fun initData() {
        viewModel.keyWord = arguments?.getString(QUERY_WORD) ?: ""
    }

    override fun initView(view: View) {
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.pageNo++
            viewModel.loadData()
        }

        viewBinding.recycler.adapter = adapter
        viewBinding.recycler.layoutManager =
            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        viewBinding.recycler.addItemDecoration(
            SimpleGapItemDecor(
                withEdge = true,
                horGap = 8.dp2px(),
                verGap = 8.dp2px()
            )
        )

        viewBinding.btnAll.checkBtn()
        viewBinding.btnVideo.unCheckBtn()
        viewBinding.btnImg.unCheckBtn()

        viewBinding.btnAll.setOnClickListener {
            viewModel.type ?: return@setOnClickListener

            viewBinding.btnAll.checkBtn()
            viewBinding.btnVideo.unCheckBtn()
            viewBinding.btnImg.unCheckBtn()
            loadData(null)
        }
        viewBinding.btnVideo.setOnClickListener {
            if (viewModel.type == PostResultVM.TYPE_VIDEO) {
                return@setOnClickListener
            }
            viewBinding.btnAll.unCheckBtn()
            viewBinding.btnVideo.checkBtn()
            viewBinding.btnImg.unCheckBtn()
            loadData(PostResultVM.TYPE_VIDEO)
        }
        viewBinding.btnImg.setOnClickListener {
            if (viewModel.type == PostResultVM.TYPE_IMAGE) {
                return@setOnClickListener
            }
            viewBinding.btnAll.unCheckBtn()
            viewBinding.btnVideo.unCheckBtn()
            viewBinding.btnImg.checkBtn()
            loadData(PostResultVM.TYPE_IMAGE)
        }

    }

    override fun initLoad() {
    }

    override fun startObserve() {
        viewModel.contentLD.observe(this) {
            if (viewModel.pageNo == 1) {
                viewBinding.recycler.visibleOrGone(it.isNotEmpty()) {
                    scrollToPosition(0)
                }
                if (it.isEmpty()) {
                    adapter.notifyItemRangeRemoved(0, 10000)
                } else {
                    adapter.refreshAll()
                }
            } else {
                adapter.notifyItemRangeChanged(viewModel.contentList.size - it.size, it.size)
            }
            if (it.isNotEmpty()) {
                viewBinding.refresher.finishLoadMore()
            } else {
                viewBinding.refresher.finishLoadMoreWithNoMoreData()
            }

            viewBinding.vEmpty.visibleOrGone(viewModel.contentList.isEmpty())

        }

        //同步点赞数据
        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) {
            if (it.postId != null) {
                for ((index, post) in viewModel.contentList.withIndex()) {
                    if (post != null && post is PostF && it.postId == post.id && it.like != post.liked) {
                        ApolloValSetExt.setApolloVal<PostF>(post, "liked", it.like)
                        ApolloValSetExt.setApolloVal<PostF>(post, "likeNumbers", it.likeCount)
                        adapter.notifyItemChanged(index)
                        break
                    }
                }
            }
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FgmSearchPostResultBinding = FgmSearchPostResultBinding.inflate(layoutInflater)

    override fun onLazyInitData() {
        viewModel.loadData()
    }

    private fun MaterialButton.checkBtn() {
        setTextColor(color(R.color.sk_red600))
        strokeWidth = 1.dp2px()
        strokeColor = ColorStateList.valueOf(color(R.color.sk_red600))
        iconTint = ColorStateList.valueOf(color(R.color.sk_red400))
        backgroundTintList = ColorStateList.valueOf(color(R.color.sk_red50))
    }

    private fun MaterialButton.unCheckBtn() {
        setTextColor(color(R.color.sk_gray500))
        strokeWidth = 0
        iconTint = ColorStateList.valueOf(color(R.color.sk_gray400))
        backgroundTintList = ColorStateList.valueOf(color(R.color.sk_gray50))
    }

    private fun loadData(type: Int?) {
        viewModel.type = type
        viewModel.pageNo = 1
        viewModel.loadData()
        viewModel.loadStartLoading()
        viewBinding.refresher.setNoMoreData(false)
    }

    companion object {

        const val QUERY_WORD = "query_word"

        fun newInstance(queryWord: String) = PostResultFragment().apply {
            arguments = bundleOf(QUERY_WORD to queryWord)
        }

    }
}